package com.unitechs.commons.annotation.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.unitechs.commons.annotation.*;
import com.unitechs.commons.constants.ZyucColorEnum;
import com.unitechs.commons.constants.ZyucExcelOperatorEnum;
import com.unitechs.commons.pojo.ExcelEntity;
import com.unitechs.commons.utils.ZyucTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 导出excel
 */
@Component
@Aspect
@Slf4j
@Order(60)
public class ExcelExportAspect {

    private static final String FORMAT = "yyyyMMddHHmmss";


    @Around("@annotation(excelExportMethod)")
    public Object aroundExcelExportMethod(ProceedingJoinPoint joinPoint, ZyucExcelExport excelExportMethod) throws Throwable {
        log.info("进入导出excel的动态代理");


        //获取返回值
        Object result = joinPoint.proceed();
        ConcurrentHashMap<String, XSSFCellStyle> cellStyleMap = new ConcurrentHashMap<>();
        //创建响应对象
        HttpServletResponse response = createHttpServletResponse();

        Class<?> elementType = getMethodReturnType(joinPoint);
        if (elementType == null) {
            return result;
        }

        log.info("elementType为：{}", elementType.getName());

        String excelName = excelExportMethod.zyucFileName() + ZyucTimeUtil.zyucGetNowTime(FORMAT);
        log.info("表名为:{}", excelName);

        JSONArray objects = convertToJSONArray(result);
        log.info("返回结果为：{}", objects);

        creatWorkbook(elementType, objects, excelName, response, cellStyleMap, excelExportMethod);

        log.info("成功执行");
        return result;
    }


    private void creatWorkbook(Class<?> elementType, JSONArray objects, String excelName, HttpServletResponse response, ConcurrentHashMap<String, XSSFCellStyle> cellStyleMap, ZyucExcelExport excelExportMethod) {

        log.info("进入了exportExcel方法");

        // 创建SXSSFWorkbook对象(excel的文档对象)
        try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
            // 设置缓存的行数，超过这个数量就将数据写入磁盘
            wb.setCompressTempFiles(true);
            //创建表一
            SXSSFSheet sheet = wb.createSheet("Sheet1"); // 创建一个名为 "Sheet1" 的工作表
            log.info("内部表名为：{}", sheet.getSheetName());
            Map<String, Field> fieldMap = new HashMap<>();
            List<String> title = creatTitle(wb, sheet, elementType, fieldMap, cellStyleMap);
            if (objects != null && !objects.isEmpty()) {
                creatBody(wb, sheet, objects, fieldMap, title, cellStyleMap);
            }
            if (!excelExportMethod.zyucToPdf()) {
                exportExcel(wb, excelName, response);
            }

        } catch (IOException e) {
            log.error("执行报错", e);
        }

    }


    private XSSFCellStyle getNewCellStyle(SXSSFWorkbook wb, ExcelEntity excel) {
        excel.setBold(false);
        excel.setFont("Arial");
        excel.setColor("");
        excel.setFontColor(ZyucColorEnum.BLACK.getHexCode());
        return createCellStyle(wb, excel);
    }

    /**
     * 创建表体
     */
    private void creatBody(SXSSFWorkbook wb, SXSSFSheet sheet, JSONArray objects, Map<String, Field> fieldMap, List<String> title, ConcurrentHashMap<String, XSSFCellStyle> cellStyleMap) {


        // 写入数据
        int rowNum = 1; // 从第二行开始，第一行已经包含了表头
        // 在循环外创建行和单元格样式
        SXSSFRow newRow;
        SXSSFCell cel;
        for (int i = 0; i < objects.size(); i++) {
            if (objects.getJSONObject(i) == null) {
                continue;
            }
            //获取一行数据
            JSONObject cellData = objects.getJSONObject(i);
            log.info("cellData:{}", cellData);

            //创建新行
            newRow = sheet.createRow(rowNum);
            for (int cellNum = 0; cellNum < fieldMap.values().size(); cellNum++) {

                //获取标题
                String header = title.get(cellNum);
                log.info("header为:{}", header);
                Field field = fieldMap.get(header);
                log.info("field为:{}", field);
                //创建第一个单元格
                cel = newRow.createCell(cellNum);

                if (field == null) {
                    continue;
                }
                ZyucExcelBody fieldAnnotation = field.getAnnotation(ZyucExcelBody.class);
                setColumnWidth(sheet,fieldAnnotation,i);

                List<ZyucExcelIf> zyucExcelIfArray = setExcelIfs(field);


                ExcelEntity excel = new ExcelEntity();
                XSSFCellStyle defStyle = getNewCellStyle(wb, excel);
                log.info("excel为1：{}", excel);

                //设置单元格格式
                setCellValueRecursive(sheet, cellData, field.getName(), cel);
                defStyle = setExcelBodyStyle(wb, excel, defStyle, fieldAnnotation, cellStyleMap);
                defStyle = creatIfExcelBodyStyle(cel, wb, excel, defStyle, zyucExcelIfArray);
                log.info("excel为2：{}", excel);
                cel.setCellStyle(defStyle);
            }

            rowNum++;
        }
    }
    private List<ZyucExcelIf>  setExcelIfs(Field field){
        ZyucExcelIf zyucExcelIf = field.getAnnotation(ZyucExcelIf.class);

        log.info("获取到的zyucExcelIf为：{}", zyucExcelIf);
        ZyucExcelIfs zyucExcelIfs = field.getAnnotation(ZyucExcelIfs.class);
        List<ZyucExcelIf> zyucExcelIfArray = new ArrayList<>();
        if (zyucExcelIfs != null && zyucExcelIfs.value().length > 0) {
            log.info("进入多条件查询");
            ZyucExcelIf[] zyucExcelIfs1 = zyucExcelIfs.value();
            zyucExcelIfArray = Arrays.asList(zyucExcelIfs1);
        } else if (zyucExcelIf != null) {
            log.info("进入单条件查询");
            zyucExcelIfArray.add(zyucExcelIf);
            log.info("zyucExcelIfArray为:{}", zyucExcelIfArray);
        }
        log.info("zyucExcelIfArray为:{}", zyucExcelIfArray);
        return zyucExcelIfArray;
    }
    private void setColumnWidth(SXSSFSheet sheet,ZyucExcelBody fieldAnnotation,int i) {
        //设置列宽
        if (fieldAnnotation!=null) {
            sheet.setColumnWidth(i, fieldAnnotation.zyucWidth());
        }else {
            sheet.setColumnWidth(i, 20 * 256);
        }
    }


    private String getCellStringValue(SXSSFCell cel) {
        DataFormatter dataFormatter = new DataFormatter();
        return dataFormatter.formatCellValue(cel);
    }

    /**
     * 设置条件格式
     */
    private XSSFCellStyle creatIfExcelBodyStyle(SXSSFCell cel, SXSSFWorkbook wb, ExcelEntity excel, XSSFCellStyle defStyle, List<ZyucExcelIf> zyucExcelIfArray) {
        log.info("进入了setIfExcelBodyStyle方法");
        Map<Integer, ZyucExcelIf> zyucExcelIfMap = new HashMap<>();
        List<Integer> sorts = new ArrayList<>();

        for (ZyucExcelIf zyucExcelIf : zyucExcelIfArray) {
            log.info("zyucExcelIf为:{}", zyucExcelIf);
            int sort = zyucExcelIf.zyucSort();
            ZyucExcelIf zyucExcelIf1 = zyucExcelIfMap.get(sort);
            if (zyucExcelIf1 == null) {
                zyucExcelIfMap.put(sort, zyucExcelIf);
                sorts.add(sort);
            } else {
                log.error("排序值不可相等");
            }
        }
        Collections.sort(sorts, Collections.reverseOrder());

        log.info("annotation为:{}", zyucExcelIfMap);
        for (Integer s : sorts) {
            ZyucExcelIf zyucExcelIf = zyucExcelIfMap.get(s);
            String operatorStr = zyucExcelIf.zyucOperator().toLowerCase().replaceAll("\\s", "");
            log.info("operatorStr为：{}", operatorStr);
            ZyucExcelOperatorEnum operator = ZyucExcelOperatorEnum.getOperatorEnum(operatorStr);
            log.info("operator为：{}", operator);
            String opeValue = zyucExcelIf.zyucOpeValue();
            log.info("opeValue为：{}", opeValue);
            String cellValue = getCellStringValue(cel);
            log.info("cellValue为：{}", cellValue);
            if (opeValue.isEmpty() || operator == null) {
                return defStyle;
            }

            boolean index = switchMethod(operator, opeValue, cellValue, cel);

            if (index) {
                upExcelEntityInfo(zyucExcelIf, excel);
                defStyle = createCellStyle(wb, excel);
            }
        }
        log.info("结束了setIfExcelBodyStyle方法");
        return defStyle;
    }

    private boolean switchMethod(ZyucExcelOperatorEnum operator, String opeValue, String cellValue, SXSSFCell cel) {
        boolean index = false;
        BigDecimal bigDecOpe = null;
        BigDecimal bigDecCell = null;
        int compare = 0;
        if (opeValue.matches("^\\d+(\\.\\d+)?$") && cellValue.matches("^\\d+(\\.\\d+)?$")) {
            bigDecOpe = new BigDecimal(opeValue);
            bigDecCell = new BigDecimal(cellValue);
            compare = bigDecCell.compareTo(bigDecOpe);
            log.info("注解值：{}，数据值：{}compare:{}", bigDecOpe, bigDecCell, compare);
        }
        log.info("opeValue：{}，cellValue：{}", opeValue, cellValue);
        switch (operator) {
            case ADD:
            case SUBTRACT:
            case MULTIPLY:
            case DIVIDE:
            case REPLACE:
                computeSwitch(operator, opeValue, cellValue, cel, bigDecOpe, bigDecCell);
                return false;
            case GREATER_THAN:
            case LESS_THAN:
            case GREATER_THAN_OR_EQUAL_TO:
            case LESS_THAN_OR_EQUAL_TO:
            case CONTAINS:
            case BETWEEN:
            case EQUALS:
            case NOT_EQUALS:
                return compareSwitch(operator, opeValue, cellValue, bigDecOpe, bigDecCell, index, compare);
            default:
                log.error("没匹配到任何符号{}", operator);
                return index;
        }
    }

    /**
     * 计算类
     */
    private void computeSwitch(ZyucExcelOperatorEnum operator, String opeValue, String cellValue, SXSSFCell cel, BigDecimal bigDecOpe, BigDecimal bigDecCell) {
        if (bigDecOpe == null || bigDecCell == null) {
            log.error("读取到的字符串不是一个数字,注解上:{},数据中:{}", opeValue, cellValue);
            return;
        }
        switch (operator) {
            case ADD:
                cel.setCellValue(bigDecCell.add(bigDecOpe).doubleValue());
                log.info("进行加操作");
                break;
            // 执行加法操作的逻辑
            case SUBTRACT:
                cel.setCellValue(bigDecCell.subtract(bigDecOpe).doubleValue());
                log.info("进行减操作");
                break;
            // 执行减法操作的逻辑
            case MULTIPLY:
                cel.setCellValue(bigDecCell.multiply(bigDecOpe).doubleValue());
                log.info("进行乘操作");
                break;
            // 执行乘法操作的逻辑
            case DIVIDE:
                cel.setCellValue(bigDecOpe.compareTo(BigDecimal.ZERO) != 0 ? bigDecCell.divide(bigDecOpe, 2, BigDecimal.ROUND_HALF_UP).doubleValue() : 0);
                log.info("进行除操作");
                break;
            //执行除法逻辑
            case REPLACE:
                String[] replaceSplit = opeValue.split("%to%");
                if (replaceSplit.length == 2) {
                    cel.setCellValue(cellValue.replaceAll(replaceSplit[0], replaceSplit[1]));
                } else if (replaceSplit.length == 1 && opeValue.endsWith("%to%")) {
                    cel.setCellValue(cellValue.replaceAll(replaceSplit[0], ""));
                }
                break;
            //执行替换操作
            default:

        }
    }

    /**
     * 比较类
     */
    private boolean compareSwitch(ZyucExcelOperatorEnum operator, String opeValue, String cellValue, BigDecimal bigDecOpe, BigDecimal bigDecCell, boolean index, int compare) {
        switch (operator) {

            case GREATER_THAN:
                //和阈值比较
                return compare > 0;
            // 执行大于操作的逻辑
            case LESS_THAN:
                return compare < 0;
            // 执行小于操作的逻辑
            case GREATER_THAN_OR_EQUAL_TO:
                return compare >= 0;
            // 执行大于等于操作的逻辑
            case LESS_THAN_OR_EQUAL_TO:
                return compare <= 0;
            // 执行小于等于操作的逻辑
            case CONTAINS:
                // 执行包含操作的逻辑
                return cellValue.contains(opeValue);
            case BETWEEN:
                String[] betweenSplit = opeValue.split("%and%");
                BigDecimal first = new BigDecimal(betweenSplit[0]);
                BigDecimal second = new BigDecimal(betweenSplit[1]);
                return betweenSplit.length == 2 && bigDecCell != null && bigDecCell.compareTo(first) + second.compareTo(bigDecCell) == 2;
            case EQUALS:
                return (bigDecOpe != null) ? compare == 0 : cellValue.equals(opeValue);
            case NOT_EQUALS:
                return (bigDecOpe != null) ? compare != 0 : !cellValue.equals(opeValue);
            default:
                return index;
        }
    }


    private void upExcelEntityInfo(ZyucExcelIf annotation, ExcelEntity excel) {
        String color = annotation.zyucColor();
        String fontColor = annotation.zyucFontColor();
        if (!color.isEmpty()) {
            excel.setColor(color);
        }
        if (!fontColor.isEmpty()) {
            excel.setFontColor(fontColor);
        }
        excel.setBold(annotation.zyucIsBold());

    }


    /**
     * 设置body单元格格式
     */
    private XSSFCellStyle setExcelBodyStyle(SXSSFWorkbook wb, ExcelEntity excel, XSSFCellStyle defStyle, ZyucExcelBody fieldAnnotation, ConcurrentHashMap<String, XSSFCellStyle> cellStyleMap) {

        if (fieldAnnotation != null) {
            String font = fieldAnnotation.zyucFont();
            String color = fieldAnnotation.zyucColor();
            String fontColor = fieldAnnotation.zyucFontColor();
            boolean isBold = fieldAnnotation.zyucIsBold();
            excel.setFontColor(fontColor);
            excel.setFont(font);
            excel.setColor(color);
            excel.setBold(isBold);
            defStyle = getXSSFCellStyle(wb, excel, cellStyleMap);
        }
        return defStyle;
    }

    /**
     * 控制单元格超限问题
     */
    private static final int MAX_RECURSION_DEPTH = 10;
    private static final int MAX_CELL_VALUE_LENGTH = 30000;

    private void setCellValueRecursive(SXSSFSheet sheet, JSONObject cellData, String propertyName, SXSSFCell cel) {
        if (cellData.containsKey(propertyName)) {
            Object value = cellData.get(propertyName);
            String cellValue = (value != null) ? value.toString() : "";

            // 如果数据超过最大长度限制，使用递归处理
            if (cellValue.length() > MAX_CELL_VALUE_LENGTH) {
                int startIndex = 0;
                int rowNum = cel.getRowIndex();

                setCellValueRecursive(sheet, cellValue, startIndex, rowNum, cel.getColumnIndex(), 1);
            } else {
                cel.setCellValue(cellValue);
            }
        }

    }

    private void setCellValueRecursive(SXSSFSheet sheet, String cellValue, int startIndex, int rowNum, int colIndex, int recursionDepth) {
        if (recursionDepth <= MAX_RECURSION_DEPTH && startIndex < cellValue.length()) {
            int endIndex = Math.min(startIndex + MAX_CELL_VALUE_LENGTH, cellValue.length());
            String subValue = cellValue.substring(startIndex, endIndex);

            // 创建新行
            SXSSFRow newRow = sheet.getRow(rowNum);
            if (newRow == null) {
                newRow = sheet.createRow(rowNum);
            }

            SXSSFCell newCell = newRow.createCell(colIndex);
            newCell.setCellValue(subValue);

            // 不再合并单元格，避免不正确的合并

            // 递归处理剩余部分，递增行号
            setCellValueRecursive(sheet, cellValue, endIndex, rowNum + 1, colIndex, recursionDepth + 1);
        }
    }



    /**
     * 创建表头
     */
    private List<String> creatTitle(SXSSFWorkbook wb, SXSSFSheet sheet, Class<?> elementType, Map<String, Field> fieldMap, ConcurrentHashMap<String, XSSFCellStyle> cellStyleMap) {
        List<String> title = new ArrayList<>();
        // 创建表头行
        SXSSFRow headerRow = sheet.createRow(0);
        AtomicInteger cellNum = new AtomicInteger(0);
        ReflectionUtils.doWithFields(elementType, field -> {
            ZyucExcelTitle fieldAnnotation = field.getAnnotation(ZyucExcelTitle.class);
            if (fieldAnnotation != null) {
                log.info("表头信息：{}", fieldAnnotation.zyucTitle());
                String font = fieldAnnotation.zyucFont();
                String color = fieldAnnotation.zyucColor();
                String fontColor = fieldAnnotation.zyucFontColor();
                boolean isBold = fieldAnnotation.zyucIsBold();
                ExcelEntity excel = new ExcelEntity();
                excel.setBold(isBold);
                excel.setFont(font);
                excel.setColor(color);
                excel.setFontColor(fontColor);
                XSSFCellStyle xssfCellStyle = getXSSFCellStyle(wb, excel, cellStyleMap);
                // 在 headerRow 的 cellNum 列创建一个单元格
                SXSSFCell headerCell = headerRow.createCell(cellNum.getAndIncrement());
                headerCell.setCellValue(fieldAnnotation.zyucTitle());
                headerCell.setCellStyle(xssfCellStyle);
                fieldMap.put(fieldAnnotation.zyucTitle(), field);
                title.add(fieldAnnotation.zyucTitle());
            }
        });
        log.info("fieldMap:{}", fieldMap);
        return title;
    }

    /**
     * 获取单元格样式
     */
    private XSSFCellStyle getXSSFCellStyle(SXSSFWorkbook wb, ExcelEntity excel, ConcurrentHashMap<String, XSSFCellStyle> cellStyleMap) {
        String cellValueKey = excel.getFont() + excel.getColor() + (excel.isBold() ? "true" : "false");
        XSSFCellStyle xssfCellStyle = cellStyleMap.get(cellValueKey);
        if (xssfCellStyle == null) {
            xssfCellStyle = createCellStyle(wb, excel);
            cellStyleMap.put(cellValueKey, xssfCellStyle);
        }
        return xssfCellStyle;
    }


    /**
     * 获取方法的返回值类型
     */
    private Class<?> getMethodReturnType(ProceedingJoinPoint joinPoint) {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取方法
        Method method = signature.getMethod();
        // 获取返回值类型
        Class<?> returnType = method.getReturnType();

        log.info("返回值类型：" + returnType.getName());

        Class<?> elementType = null;
        // 如果返回类型是 List
        if (List.class.isAssignableFrom(returnType) || Set.class.isAssignableFrom(returnType)) {
            // 获取泛型参数类型
            Type genericReturnType = method.getGenericReturnType();
            if (genericReturnType instanceof ParameterizedType) {
                Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
                if (actualTypeArguments.length > 0 && actualTypeArguments[0] instanceof Class) {
                    elementType = (Class<?>) actualTypeArguments[0];
                }
            }
        } else {
            elementType = returnType;
        }
        return elementType;
    }

    /**
     * 返回值转JSONArray
     */
    private JSONArray convertToJSONArray(Object result) {
        if (result instanceof JSONArray) {
            return (JSONArray) result;
        } else {
            JSONArray jsonArray = new JSONArray();

            if (result instanceof Collection<?>) {
                Collection<?> listResult = (Collection<?>) result;
                jsonArray.addAll(listResult);
            } else {
                jsonArray.add(result);
            }
            return jsonArray;
        }
    }


    /**
     * 创建响应对象
     */
    private HttpServletResponse createHttpServletResponse() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        if (requestAttributes instanceof ServletRequestAttributes) {
            log.info("获取到了响应对象:{}", ((ServletRequestAttributes) requestAttributes).getResponse());
            return ((ServletRequestAttributes) requestAttributes).getResponse();
            // 现在可以安全地使用 response 对象
        } else {
            log.info("没有获取到响应对象");
            // 处理不是 ServletRequestAttributes 的情况
            return null;
        }
    }

    /**
     * 设置响应头，包括字符编码和文件名编码
     */
    private void setResponseHeaders(HttpServletResponse response, String excelName) throws UnsupportedEncodingException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");

        // 设置文件名，确保中文文件名不乱码
        String encodedFileName = URLEncoder.encode(excelName + ".xlsx", String.valueOf(StandardCharsets.UTF_8));
        response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
    }

    /**
     * 导出excel
     */
    private void exportExcel(SXSSFWorkbook wb, String excelName, HttpServletResponse response) {
        log.info("进入了exportExcel方法");
        try {
            // 导出 Excel 数据
            if (response != null) {
                // 设置字符编码和内容类型
                String newFileName = new String(excelName.getBytes(), String.valueOf(StandardCharsets.UTF_8));
                setResponseHeaders(response, newFileName);
                try (OutputStream out = response.getOutputStream()) {
                    wb.write(out);
                }
            }
        } catch (IOException e) {
            log.error("执行报错", e);
            // 在这里可以根据实际需求进行异常处理，例如向用户返回错误信息
        }
        log.info("exportExcel方法执行结束");
    }

    private XSSFCellStyle createCellStyle(SXSSFWorkbook wb, ExcelEntity excel) {
        String color = getColorCode(excel.getColor());
        String fontColor = getColorCode(excel.getFontColor());
        String fontName = excel.getFont();
        boolean bold = excel.isBold();

        XSSFCellStyle style = (XSSFCellStyle) wb.createCellStyle();
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setAlignment(HorizontalAlignment.CENTER);

        XSSFFont font = (XSSFFont) wb.createFont();
        font.setFontName(fontName);
        font.setBold(bold);
        font.setFontHeightInPoints((short) 12);
        if (fontColor != null && !fontColor.isEmpty()) {
            try {
                java.awt.Color awtColor = java.awt.Color.decode(fontColor);
                XSSFColor xssfColor = new XSSFColor(new byte[]{(byte) awtColor.getRed(), (byte) awtColor.getGreen(), (byte) awtColor.getBlue()}, new DefaultIndexedColorMap());
                font.setColor(xssfColor);
            } catch (NumberFormatException e) {
                log.error("生成字体颜色异常");
            }
        }

        style.setFont(font);
        style.setLocked(true);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setWrapText(true);

        // 设置单元格填充颜色
        if (color != null && !color.isEmpty()) {
            try {
                // 解析颜色字符串，例如 "#RRGGBB"
                java.awt.Color awtColor = java.awt.Color.decode(color);

                // 使用 XSSFColor 直接设置 RGB 值
                XSSFColor xssfColor = new XSSFColor(new byte[]{(byte) awtColor.getRed(), (byte) awtColor.getGreen(), (byte) awtColor.getBlue()}, new DefaultIndexedColorMap());

                // 设置填充颜色
                style.setFillForegroundColor(xssfColor);
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            } catch (NumberFormatException e) {
                // 处理解析异常，或者根据需求进行其他处理
                log.error("生成单元格样式异常");
            }
        }

        return style;
    }

    /**
     * 将字符串颜色转编码
     */
    private static String getColorCode(String colorName) {
        try {
            if (!colorName.trim().startsWith("#")) {
                // 尝试从 ZyucColorEnum 中获取对应的枚举值
                ZyucColorEnum colorEnum = Arrays.stream(ZyucColorEnum.values())
                        .filter(enumValue -> enumValue.getCode().equalsIgnoreCase(colorName) || enumValue.getName().equals(colorName))
                        .findFirst()
                        .orElse(null);

                // 如果找到对应的枚举值，返回它的十六进制代码
                if (colorEnum != null) {
                    return colorEnum.getHexCode();
                }
            }
        } catch (Exception e) {
            log.error("颜色转换失败", e);
        }
        // 如果无法转换或找不到对应颜色，返回原始颜色名称
        return colorName;
    }

}
